"""
    Views to allow you to do stuff with cadets
"""
from django.http import Http404, HttpResponseRedirect

from badmin.models import Cadet
from badmin.forms import CadetForm

from badmin.views.helpers import respond

def list(request):
  # # Testing code to populate the data store
  # new_cadet = Cadet(first_name='Bob', last_name='Grigg')
  # new_cadet.put()
  # new_cadet = Cadet(first_name='Bob', last_name='Miller')
  # new_cadet.put()
  # new_cadet = Cadet(first_name='Windy', last_name='Miller')
  # new_cadet.put()
  cadet_list = Cadet.all().fetch(1000)
  template_values = {
    'instance_list': cadet_list,
  }
  return respond(request, 'badmin/cadet/list.html', template_values)
  
def new(request):
  if request.method == 'POST':
    form = CadetForm(request.POST)
    if form.is_valid():
      cadet = Cadet(**form.cleaned_data)
      cadet.put()
      return HttpResponseRedirect(cadet.view_url())
  else:
    form = CadetForm()
  template_values = {
    'form': form,
  }
  return respond(request, 'badmin/cadet/new.html', template_values)


def view(request, first_name, last_name):
  cadet = Cadet.get_by_name(first_name, last_name)
  if not cadet:
    raise Http404
  template_values = {
    'instance': cadet,
  }
  return respond(request, 'badmin/cadet/view.html', template_values)

def edit(request, first_name, last_name):
  """docstring for edit"""
  cadet = Cadet.get_by_name(first_name, last_name)
  if not cadet:
    raise Http404

  if request.method == 'POST':
    form = CadetForm(request.POST)
    if form.is_valid():
      for key, value in form.cleaned_data.items():
        setattr(cadet, key, value)
      cadet.put()
      return HttpResponseRedirect(cadet.view_url())
  else:
    form = CadetForm(initial={'first_name':cadet.first_name,
                              'last_name':cadet.last_name,})
  template_values = {
    'instance': cadet,
    'form': form,
  }
  return respond(request, 'badmin/cadet/edit.html', template_values)

def delete(request, first_name, last_name):
  cadet = Cadet.get_by_name(first_name, last_name)
  if not cadet:
    raise Http404
  if request.method == 'POST':
    cadet.delete()
    return HttpResponseRedirect(cadet.list_url())
  
  template_values = {
    'instance': cadet,
  }
  return respond(request, 'badmin/cadet/delete.html', template_values)